package com.grass.finding.utils;


import com.google.gson.Gson;
import com.grass.finding.common.ErrorCode;
import com.grass.finding.exception.BusinessException;
import com.grass.finding.model.wxApiModel.Code2Session;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;


public class WXUtil {

    /**
     * 获取用户openID
     * @param js_code 前端传入的openID
     * @return 空字符串代表没有获取到openID,否则返回获取的openID
     */
    public static String getOpenID(String js_code) {
        Code2Session code2Session = getCode2Session(js_code);
        if(code2Session != null){
            return code2Session.getOpenid();
        }
        return null;
    }

    public static String getOpenId(HttpServletRequest request){
        String openId = (String) request.getSession().getAttribute("openId");
        // 如果openid不存在
        if(openId == null){
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        return openId;
    }
    public static Code2Session getCode2Session(String js_code){
        //拼接请求地址
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=wx0f722677458fdfa2&" +
                "secret=4e19ee57750e61c28ef51b1acdb18e61&" +
                "js_code=" + js_code +
                "&agrant_type=authorization_code";
//        获取openID的响应体
        String responseBody = HttpUtil.doGet(url);
        Gson gson = new Gson();
        Code2Session res = gson.fromJson(responseBody, Code2Session.class);
        if (res==null){
            throw new RuntimeException("获取openID失败");
        }
        return res;
    }
}
